<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" scanType="1" :leftType="'1'"  @clickLeftBack="clickLeftBack" :title="$t('consumo.interOrgTransferOut')" rightText="扫描记录"
				@clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<scroll-view class="scroll-view_H" scroll-y>
				
			<!-- <view class="page-auto" :style="'height: calc(100vh - '+ navHeight +'px);'"> -->
				<!-- 调拨单信息 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('consumo.outboundDeliveryInfor')}}
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('consumo.outboundDeliveryOrderNo')}}：</text>
						<text>{{data.warehouseInfo.dnCode}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('pageTranslation.deliveryDate')}}：</text>
						<text>{{data.warehouseInfo.dnDate}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('smashRemoval.deliveredTotal')}}：</text>
						<text>{{data.warehouseInfo.sumQty}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('distributedEnter.quantityOutStorage')}}：</text>
						<text>{{data.warehouseInfo.sumScan}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('distributedOut.organizationOut')}}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.organizationOutList"
							:placeholder="$t('stockManage.placeholder')" :isJSON="true" keyName="text" v-model="data.selectedOut"
							@select="selectOut"></superweiCombox>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('distributedOut.organizationIn')}}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.organizationEnterList"
						:placeholder="$t('stockManage.placeholder')" :isJSON="true" keyName="text" v-model="data.selectedEnter"
							@select="selectEnter"></superweiCombox>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{$t('distributedEnter.materialCoded')}}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode" type="search" :disabled="data.warehouseInfo.sumQty == data.warehouseInfo.sumScan"
							 :placeholder="$t('distributedOut.pleaseMaterial')" @confirm="confirm('barcode')" @iconClick="iconClick($event,'barcode')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{$t('distributedOut.palletBarcode')}}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.trayCode" type="search" :disabled="data.barcode == ''"
							:placeholder="$t('distributedOut.pleasePallet')" @confirm="confirm('tray')" @iconClick="iconClick($event,'tray')">
						</uni-easyinput>
					</view>
				</view>
				<!-- 当前扫描条码 -->
				<view class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{$t('distributedOut.atPresent')}}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialCoded')}}：</text>{{data.currentBarcode.barcode}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{data.currentBarcode.spec}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{data.currentBarcode.materialcode}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{data.currentBarcode.materialname}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('translationImage.traySize')}}：</text>{{data.currentBarcode.qrCode}}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{data.currentBarcode.currentqty}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text>{{data.currentBarcode.unit}}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedOut.warehouse')}}：</text>{{data.currentBarcode.warehousecode}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{data.currentBarcode.locatcode}}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding:0rpx 50rpx 20rpx;">{{$t('consumo.outboundDeliveryInfor')}}</text>
					<view class="gui-title-line"></view>
				</view>
				<uni-card class="element-auto gui-margin-top card-my">
					<view class="element-auto" style="height: 500rpx">
						<zb-table :columns="data.column" :stripe="true" :border="true"
							:data="tableData.list" @customLook="customBtnFn" :cell-style="cellStyle"
							:cell-header-style="cellHeaderStyle">
						</zb-table>
					</view>
				</uni-card>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box" @click="submit">
					<view class="page-bottomBtn bottomBtn-bgcolor-green">
						{{$t('calendar.submit')}}
					</view>
				</view>
			<!-- </view> -->
		</scroll-view>
			<gui-top-message ref="guitopmsg">
				<view class="gui-bg-red">
					<text style="line-height:88rpx; font-size:26rpx; text-align:center;"
						class="gui-block-text gui-color-white gui-icons">&#xe646; {{$t('smashRemoval.codesRepeatedly')}}</text>
				</view>
			</gui-top-message>
			<!-- 普通弹窗 -->
			<uni-popup ref="popupDetail" type="center">
				<view class="input-dialog-box"
					style="padding: 40rpx 20rpx 20rpx 20rpx;border-radius: 22rpx;width: 600rpx;">
					<uni-icons class="popup-close-icons" type="closeempty" color="#9C9C9C" size="26"
						@click="closePopup"></uni-icons>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text> {{data.popupData.materialCode}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text> {{data.popupData.materialName}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text> {{data.popupData.spec}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('translationImage.totalDocuments')}}：</text> {{data.popupData.saleQty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.quantityOutStorage')}}：</text> {{data.popupData.scanQty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.scannedQuantity')}}：</text> {{data.popupData.currentscanQty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text> {{data.popupData.saleUnit}}
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import {ref,reactive,onMounted,toRaw,watchEffect,computed,watch} from 'vue'
import {navigate} from '@/utils/routerSkip.js';
import {getMaterialCodeInfo,findWmsDnHById,checkQrCodeIsBindWMS,sdistributedCallOut} from '@/api/api.js'
import pdaScan from '@/hooks/pdaScan.js'
import {getDataDictionaryFn,pitchOnFn,sortClassMaterialcode} from '@/utils/index.js'
import superweiCombox from '@/components/superweiCombox';
import tableColor from '@/hooks/tableColor.js';
import graceJS from "@/Grace6/js/grace.js";
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN, OPERATION_CHECK } from '@/constant/index.js'
import {useStore} from "vuex";
import { onBackPress } from '@dcloudio/uni-app';
//JS国际化引入
import { useI18n } from 'vue-i18n';
components: {
	superweiCombox}
const { t } = useI18n();

const { scan } = pdaScan()
let {
	tableData} = tableColor();
const {
	cellStyle,
	cellHeaderStyle} = tableColor();
let guitopmsg = ref(null)
let popupDetail = ref(null)
const props = defineProps({
	id:String
})
let store = useStore();
let data = reactive({
	value: ['1'],
	inputType: 'barcode',
	popupData: {},
	scanNum: 0,
	warehouseInfo: {},
	warehouseList: [],
	organizationEnterList: [],
	organizationOutList: [],
	selectedOut: '',
	selectedEnter: '',
	outId: '',
	EnterId: '',
	warehouse: '',
	barcode: '',
	trayCode: '',
	currentBarcode: {},
	column: [{
		name: 'age',
		type: 'ailibtn',
		label: t('translationImage.operation'),
		scanValue: '',
		fixed: true,
		width: 80,
	},
	{
		name: 'materialCode',
		label: t('distributedEnter.materialCode'),
		fixed: true,
		width: 100,
		emptyString: '--'
	},
	{
		name: 'materialName',
		label: t('distributedEnter.materialName'),
		width: 120,
	},
	{
		name: 'spec',
		label: t('distributedEnter.materialSpec'),
		width: 240,
	},
	{
		name: 'saleUnit',
		label: t('distributedEnter.uom'),
		width: 60,
	},
	{
		name: 'saleQty',
		label: t('translationImage.totalDocuments'),
		width: 90,
	},
	{
		name: 'scanQty',
		label: t('distributedEnter.quantityOutStorage'),
		width: 120,

	},
	{
		name: 'currentscanQty',
		label: t('distributedEnter.scannedQuantity'),
		width: 120,
	}
	]
})
data.scanList = computed(() => {
	return store.state.distributedOutData
})
const navHeight = computed(() => {
	return store.state.navHeight
})
watch(() => data.scanList, (newVal, oldVal) => {
	let tepData = toRaw(newVal)
	let list = sortClassMaterialcode(tepData)
	if (list.length) {
		let tepList = []
		list.forEach(x => {
			let item = {
				child: x,
				currentqty: 0
			}
			x.forEach(k => {
				item.materialcode = k.materialcode
				item.materialname = k.materialname
				item.spec = k.spec
				item.unit = k.unit
				item.housecode = k.housecode
				item.currentqty += Number(k.currentqty)
			})
			tepList.push(item)
		});
		tableData.list.forEach(x => {
			tepList.forEach(k => {
				if (k.materialcode == x.materialCode) {
					x.currentscanQty = k.currentqty
				}
			})
		})
		tableData.list.map((item, index) => {
			if (item.materialCode == data.currentBarcode.materialcode) {
				tableData.list.unshift(tableData.list.splice(index, 1)[0]);
			}
		})
	} else {
		tableData.list.forEach(x => {
			x.currentscanQty = 0
		})
	}
}, {
	immediate: true,
	deep: true
});
onMounted(() => {
	uni.$on('scancodedate', (res) => {
		if (data.warehouseInfo.sumQty == data.warehouseInfo.sumScan) return
		if (data.inputType === 'barcode') {
			data.barcode = res.code
			getCode(res.code, 'pda')
		} else {
			if (res.code.length > 9) {
				uni.showToast({
					title: t('Common.scanerror'),
					icon: 'none'
				})
				return
			}
			data.trayCode = res.code
			checkQrCodeIsBindWMSFn(res.code, 'pda')
		}

	})
	getInitData()
	findWmsDnHByIdFn()
})
onBackPress((options) => {
	if (options.from == 'backbutton') {
		navBackCheck()
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit('removeDistributedOutData')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
// 检查木托盘有没有被绑定
const checkQrCodeIsBindWMSFn = (code) => {
	// 判断物料条码有没有去搜索
	if (data.scanNum == 0) {
		uni.showToast({
			title: t('JsInternational.searchMatterial'),
			icon: 'none'
		})
		return
	}
	// 判断这个托盘本次有没有绑定过
	let isBind = data.scanList.some(x => x.qrCode == code);
	if (isBind) {
		uni.showToast({
			title: t('JsInternational.trayBlinded'),
			icon: 'none'
		})
		return
	}
	let parmes = {
		qrCode: data.trayCode
	}
	checkQrCodeIsBindWMS(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '组织间调出'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_CHECK
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			data.currentBarcode.qrCode = data.trayCode;
			store.commit('addDistributedOutData', data.currentBarcode);
			data.barcode = ''
			data.trayCode = ''
			uni.showToast({
				title: t('JsInternational.blind'),
				icon: 'none'
			})
			data.inputType = 'barcode'
			data.scanNum = 0
		} else {
			uni.showToast({
				title: res.message,
				icon: 'none'
			})
		}
	})
}
// 获取code
const getCode = (code, type) => {
	// 判断这个托盘本次有没有绑定过
	let isBind = data.scanList.some(x => x.barcode == code);
	if (isBind) {
		uni.showToast({
			title: t('JsInternational.scanned'),
			icon: 'none'
		})
		return
	}
	let parmes = {
		barcode: code,
		selectType: 'UpperBasMaterial',
		barcodestatus: '1',
		dnHId: props.id
	}
	getMaterialCodeInfo(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '组织间调出'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			// 判断该条码对应的单据还剩多少数量
			let tep = tableData.list.filter(x => x.materialCode == res.data.materialcode);
			let bool = tableData.list.some((item) => {
				return item.materialCode == res.data.materialcode
			})
			if (!bool) {
				uni.showToast({ title: t('materials.materialIsNot'), icon: "none" });
				return
			}
			if (tep.length) {
				// 筛选出和当前扫码一直的物料并提位
				if (tableData.list.length && tableData.list.length != 1) {
					for (var i = 0; i < tableData.list.length; i++) {
						var item = {}
						if (tableData.list[i].materialCode === res.data.materialcode) {
							item = tableData.list[i]
							tableData.list.splice(i, 1);
							tableData.list.unshift(item)
							break;
						}
					}
				}
				let num = Number(tep[0].saleQty) - Number(tep[0].scanQty) - tep[0].currentscanQty;
				if (num < 0) return uni.showToast({ title: t('JsInternational.deliveryMaterial'), icon: 'none', duration: 1500 })
				let subNum = num - res.data.currentqty;
				if (subNum < 0) return uni.showToast({ title: t('materials.scannedBarcodes') + `${tep[0].materialName}` + t('hardware.receiptsQty'), icon: 'none', duration: 2000 })
			}
			data.scanNum++
			if (data.scanNum > 1) {
				guitopmsg.value.open();
				return;
			}
			data.currentBarcode = res.data
			data.value = ['0']
			data.inputType = 'tray'
		} else {
			uni.showToast({
				title: res.message,
				icon: 'none'
			})
		}
	})
}
// 获得焦点
const getFocus = (type) => {
	data.inputType = type;
}
// 用户调起相机扫码
const iconClick = async (type, inputType) => {
	data.inputType = inputType;
	if (type === 'suffix') {
		let code = await scan()
		if (inputType === 'barcode') {
			data.barcode = code
			getCode(code, 'scan')
		} else {
			if (code.length > 9) {
				uni.showToast({
					title: t('Common.scanerror'),
					icon: 'none'
				})
				return
			}
			checkQrCodeIsBindWMSFn(code, 'scan')
		}
	}
}
// 用户点击键盘上搜索
const confirm = (type) => {
	data.inputType = type;
	let code = type == 'barcode' ? data.barcode : data.trayCode
	if (data.inputType === 'barcode') {
		getCode(code, 'keydown')
	} else {
		if (code.length > 9) {
			uni.showToast({
				title: t('Common.scanerror'),
				icon: 'none'
			})
			return
		}
		checkQrCodeIsBindWMSFn(code, 'keydown')
	}

}
// 获取调出单详情
const findWmsDnHByIdFn = () => {
	let parmes = {
		id: props.id
	}
	findWmsDnHById(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '组织间调出'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_LOOK
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			data.warehouseInfo = res.data;
			let tep = res.data.wmsDnDS
			tableData.list = tep.map(x => {
				x.currentscanQty = 0
				return x
			});
		} else {
			uni.showToast({
				title: res.message,
				icon: 'none'
			})
		}
	})
}
const selectEnter = (e) => {
	this.EnterId = e.value
}
const selectOut = (e) => {
	this.outId = e.value
}
const submit = () => {
	if (!data.scanList.length) {
		uni.showToast({
			title: t('pageTranslation.plsScanThe'),
			icon: 'none'
		})
		return
	}
	let list = data.scanList.map(x => {
		x.materialCode = x.materialcode
		x.currentQty = x.currentqty
		return x
	})
	let parmes = {
		dnHId: props.id,
		barcodes: list,
		dnTypeCode: 'sjc',
		sourceBillCode: data.warehouseInfo.dnCode
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	sdistributedCallOut(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '组织间调出'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: 'none',
				duration: 2000,
				complete: () => {
					store.commit('removeDistributedOutData')
					setTimeout(function () {
						uni.navigateBack()
					}, 1000);
					// uni.navigateBack()
				}
			})
		} else {
			uni.showToast({
				title: res.message,
				icon: "none"
			});
		}
	})

}
const getInitData = async () => {
	// 获取调入组织信息
	data.organizationOutList = await getDataDictionaryFn('TransferOutOrganization')
	let tepSelect1 = pitchOnFn(data.organizationOutList)
	data.selectedOut = tepSelect1[0].text
	data.outId = tepSelect1[0].value

	// 获取调出组织信息
	data.organizationEnterList = await getDataDictionaryFn('OrganizationalInformation')
	let tepSelect2 = pitchOnFn(data.organizationEnterList)
	data.selectedEnter = tepSelect2[0].text
	data.EnterId = tepSelect2[0].value
}
const clickRight = () => {
	navigate({
		url: '/pages/distributed/outSweepRecord'
	})
}
const customBtnFn = (item, index) => {
	data.popupData = item;
	popupDetail.value.open()
}
const closePopup = () => {
	popupDetail.value.close()
}
const rowClick = (row, index) => {
}
</script>

<style scoped lang="scss">
.scroll-view_H{
	position: fixed;
	top: 48px;
	bottom: 100rpx;
	left: 0px;
	width: 100%;
}
.page-bottom-box{
	position: fixed;
	left: 0px;
	bottom: 0px;
	z-index: 2;
	width: 100%;
}
</style>
